package com.example.clocktest

import android.app.AlarmManager
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.app.NotificationCompat
import com.example.clocktest.ui.theme.ClockTestTheme
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class MainActivity : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            ClockTestTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    ReminderScreen(innerPadding = innerPadding)
                }
            }
        }
    }
}

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
        ReminderScreen(innerPadding = innerPadding)
    }
}

@Composable
fun ReminderScreen(innerPadding: PaddingValues) {
    val context = LocalContext.current // 在 Composable 函数中获取上下文

    var countdownTime by remember { mutableStateOf(10L) } // 倒计时时间，单位为秒
    val coroutineScope = rememberCoroutineScope()

    var text by remember { mutableStateOf("") } // 用于存储输入的文本

    var repos by remember { mutableStateOf<List<Repo>?>(null) }
    var error by remember { mutableStateOf<String?>(null) }

    var result by remember { mutableStateOf("") }

    Column(
        modifier = Modifier
            .padding(innerPadding) // 应用内边距
            .fillMaxSize()
            .padding(16.dp),
//        verticalArrangement = Arrangement.Center,
        verticalArrangement = Arrangement.SpaceEvenly,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Button(onClick = {
            coroutineScope.launch {
                try {
                    val sharedPreferences = context.getSharedPreferences("cookie_prefs", Context.MODE_PRIVATE)
                    val cookie = sharedPreferences.getString("cookie", null)
                    println("JSESSIONID" + cookie)

                    val apiResponse = RetrofitClient2.apiService.getRawData()
                    if (apiResponse.isSuccessful && apiResponse.body() != null) {
                        result = apiResponse.body()!!.string() // 将 ResponseBody 转换为字符串
                        error = null
                    } else {
                        result = ""
                        error = "Error:"
                    }
                } catch (e: Exception) {
                    result = ""
                    error = "Error: ${e.message}"
                }
            }
        }) {
            Text("test post")
        }

        if (result != "") {
            Text("result: ${result}")
        } else if (error != null) {
            Text(error!!)
        }

        Button(onClick = {
            coroutineScope.launch {
                try {
                    val response = RetrofitClient.apiService.getUserRepos("octocat")
                    if (response.isSuccessful && response.body() != null) {
                        repos = response.body()
                        error = null
                    } else {
                        repos = null
                        error = "Error: ${response.code()}"
                    }
                } catch (e: Exception) {
                    repos = null
                    error = "Error: ${e.message}"
                }
            }
        }) {
            Text("Fetch Repos")
        }

        if (repos != null) {
            Text("Repos Count: ${repos!!.size}")
        } else if (error != null) {
            Text(error!!)
        }

        Row() {
            Text(
                text = "1",
                color = Color.Blue,
                fontSize = 26.sp,
                modifier = Modifier.width(50.dp)
            )
            Text(
                text = "2",
                color = Color.Blue,
                fontSize = 26.sp
            )
            Text(
                text = "3",
                color = Color.Blue,
                fontSize = 26.sp
            )
        }
        Text(
            text = "定时提醒",
            color = Color.Blue,
            fontSize = 26.sp
        )
        Button(onClick = {
            Toast.makeText(context, text, Toast.LENGTH_SHORT).show()
        }) {
            Text("测试按钮")
        }

        TextField(
            value = text,
            onValueChange = { text = it },
            label = { Text("Enter text") },
            placeholder = {
                Text(text = "Type something here")
            },
//            modifier = Modifier.fillMaxWidth()
        )

        Image(
            painter = painterResource(id = R.drawable.img),
            contentDescription = null
        )

        CircularProgressIndicator()

        LinearProgressIndicator()

        Spacer(modifier = Modifier.height(16.dp))
        Text(text = "剩余时间: $countdownTime 秒")
        Button(onClick = { setAlarm(context) }) {
            Text("设置提醒")
        }
        Button(onClick = { cancelAlarm(context) }) {
            Text("取消提醒")
        }
        Button(onClick = {
            coroutineScope.launch {
                countdownTime = 10 // 设置倒计时初始值
                while (countdownTime > 0) {
                    delay(1000) // 每秒更新一次
                    countdownTime-- // 减少倒计时时间
                }
//                 倒计时结束，设置提醒
                setAlarm(context)
            }
        }) {
            Text("测试倒计时")
        }
    }
}

data class Repo(
    val name: String,
    val description: String
)

private fun test2(context: Context) {
    val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
    val intent = Intent(context, AlarmReceiver::class.java)
    val pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_IMMUTABLE)

    alarmManager.setExact(AlarmManager.RTC_WAKEUP, 100, pendingIntent)
}

private fun test(context: Context) {
    Toast.makeText(context, "提醒已设置1111", Toast.LENGTH_SHORT).show()
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val channelId = "reminder_channel"
        val channelName = "Reminder Channel"
        val channel =
            NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT)
        val notificationManager =
            context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.createNotificationChannel(channel)
        val notification =
            NotificationCompat.Builder(context, channelId).setSmallIcon(R.drawable.ic_notification)
                .setContentTitle("提醒").setContentText("12311111111111111111111111")
                .setPriority(NotificationCompat.PRIORITY_DEFAULT).build()
        notificationManager.notify(1, notification)
    }
}

private fun setAlarm(context: Context) {
    val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
    val intent = Intent(context, AlarmReceiver::class.java)
    intent.putExtra("state", 1)
    val pendingIntent = PendingIntent.getBroadcast(
        context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
    )

    val triggerAtMillis = System.currentTimeMillis() + 100 // 100毫秒触发
    alarmManager.set(AlarmManager.RTC_WAKEUP, triggerAtMillis, pendingIntent)
    Toast.makeText(context, "提醒已设置1111", Toast.LENGTH_SHORT).show()
}

private fun cancelAlarm(context: Context) {
    val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
    val intent = Intent(context, AlarmReceiver::class.java)
    intent.putExtra("state", 2)
    val pendingIntent = PendingIntent.getBroadcast(
        context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
    )

    val triggerAtMillis = System.currentTimeMillis()
    alarmManager.set(AlarmManager.RTC_WAKEUP, triggerAtMillis, pendingIntent)
}
